package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

func worker(ctx context.Context) {

loop:
	for {
		fmt.Println("worker")
		go worker2(ctx)
		time.Sleep(time.Second)
		select {
		// 等待上级的通知
		case <-ctx.Done():
			break loop
		default:
		}
	}
	// 如何接收外部命令实现退出
	wg.Done()
}

func worker2(ctx context.Context) {
loop:
	for {
		fmt.Println("worker2")
		time.Sleep(time.Second)
		select {
		// 等待上级的通知
		case <-ctx.Done():
			break loop
		default:
		}
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	wg.Add(1)
	go worker(ctx)
	// 如何优雅的结束goroutine
	time.Sleep(time.Second * 5)
	// 通知子goroutine结束
	cancel()
	wg.Wait()
	fmt.Println("over")
}
